import { ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { IS_PUBLIC_KEY } from '../decorator/public.decorator';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private reflector: Reflector) {
    super();
  }

  // 判断是否为公共路由
  canActivate(context: ExecutionContext) {
    // 获取路由上的IS_PUBLIC_KEY装饰器
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    // 如果是公共路由，则返回true
    if (isPublic) {
      return true;
    }

    // 否则调用父类的canActivate方法
    return super.canActivate(context);
  }
}
